<template>
    <div>
        <el-row>
            <el-col :span="4">
                <el-input v-model="input2"
                    style="width: 230px; height: 30px; padding-left: 30px;  margin-bottom: 10px; " placeholder="搜索"
                    :prefix-icon="Search" @keyup.enter="searchMethod" />
                <el-tree style="max-width: 600px;margin-left: 20px; " :data="rootData" :props="defaultProps"
                    @node-click="handleNodeClick" />

            </el-col>
            <!-- 分割线 但是不显示 -->
            <el-divider direction="vertical" style="height: 100%;"></el-divider>
            <!-- 用户表格右侧 -->
            <el-col :span="18">

                <!-- 搜索部分 -->
                <el-row :gutter="10" class="search-section">
                    <el-col :span="5">
                        <el-form-item label="用户名称：">
                            <el-input v-model="filters.name" placeholder="请输入用户名称"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="手机号码：">
                            <el-input v-model="filters.tel" placeholder="请输入手机号码"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="状态">
                            <el-select v-model="filters.status" placeholder="请选择状态">
                                <el-option label="正常" :value="true"></el-option>
                                <el-option label="停用" :value="false"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="开始时间：">
                            <el-input v-model="filters.createTime" placeholder="请输入开始时间"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-button type="primary" @click="search" :icon="Search">搜索</el-button>
                        <el-button @click="reset" :icon="Refresh">重置</el-button>
                    </el-col>
                </el-row>

                <!-- 按钮部分 deleteSelectedNews-->
                <div class="button-section">
                    <el-button type="primary" plain :icon="Plus" @click="openAddDialog">新增</el-button>
                    <el-button type="success" plain :icon="Edit" @click="editSelectedMeeting">修改</el-button>
                    <el-button type="danger" plain :icon="Delete" @click="deleteSelectedMeeting">删除</el-button>
                    <el-button type="info" plain :icon="Upload" @click="triggerFileInput">导入</el-button>
                    <input type="file" ref="fileInput" @change="handleFileUpload" style="display: none"
                        accept=".xlsx,.xls,.csv" />
                    <el-button type="warning" plain :icon="Download" @click="exportExcle"
                        style="margin-left: 10px;">导出</el-button>
                </div>
                <!-- 列表表格 -->
                <el-table :data="userListWithPagination" style="width: 100%" ref="multipleTable"
                    @selection-change="handleSelectionChange">

                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column prop="id" label="用户编号" width="100"></el-table-column>
                    <el-table-column prop="name" label="用户名称" width="100"></el-table-column>
                    <el-table-column prop="nickname" label="用户昵称" width="100"></el-table-column>
                    <el-table-column prop="departmentId" label="部门"></el-table-column>
                    <el-table-column prop="tel" label="手机号码"></el-table-column>
                    <!-- 状态开关列 -->
                    <el-table-column label="状态" width="100">
                        <template #default="{ row }">
                            <el-switch v-model="row.status" active-color="#13ce66" inactive-color="#ff4949"
                                @change="handleStatusChange(row)">
                            </el-switch>
                        </template>
                    </el-table-column>

                    <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>

                    <el-table-column fixed="right" label="操作" width="150">
                        <template #default="scope">
                            <div class="operation-buttons">
                                <el-button type="primary" @click="editUsers(scope.$index, scope.row)" link size="small"
                                    :icon="EditPen">修改</el-button>
                                <el-button type="primary" @click="deleteUsers(scope.$index, scope.row)" link
                                    size="small" :icon="Delete">删除</el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页 -->
                <div class="pagination-container">
                    <el-pagination class="pagination-fixed" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange" :current-page="pageination.currentPage"
                        :page-sizes="[10, 15, 20, 25, 30]" :page-size="pageination.pageSize"
                        layout="total, sizes, prev, pager, next" :total="pageination.total">
                        <!--  style="text-align: center;" -->
                    </el-pagination>
                </div>
                <!-- 添加用户 -->
                <el-dialog v-model="visible" title="添加用户" width="60%" @close="resetForm()">
                    <div>
                        <el-form :model="addFormData" label-width="90px" :rules="rules" ref="ruleForm">

                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="用户昵称" prop="nickname">
                                        <el-input v-model="addFormData.nickname" placeholder="请输入用户昵称"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="上级部门">
                                        <el-select v-model="addFormData.companyId" placeholder="上级部门"
                                            @change="fetchDepartmentList($event)">
                                            <el-option v-for="item in tableDataTree" :key="item.companyId"
                                                :label="item.name" :value="item.companyId" />
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="归属部门">
                                        <el-select v-model="addFormData.departmentId" placeholder="归属部门">
                                            <el-option v-for="item in departmentData" :key="item.id" :label="item.name"
                                                :value="item.id" />
                                            <el-option v-if="!departmentData.length" disabled label="暂无部门，请先添加部门"
                                                value="null" />
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="手机号码">
                                        <el-input v-model="addFormData.tel" placeholder="请输入手机号码"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="邮箱">
                                        <el-input v-model="addFormData.email" placeholder="请输入邮箱"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="用户名称" prop="name">
                                        <el-input v-model="addFormData.name" placeholder="请输入用户名称"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="用户密码" prop="pwd">
                                        <!-- 密码输入框，包含切换可见性的眼睛图标 -->
                                        <el-input v-model="addFormData.pwd" placeholder="请输入用户密码" show-password>
                                        </el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="用户性别">
                                        <el-select v-model="addFormData.gender" placeholder="请选择性别">
                                            <el-option label="男" :value="true"></el-option>
                                            <el-option label="女" :value="false"></el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="状态">
                                        <el-radio-group v-model="addFormData.status">
                                            <el-radio :value="true">正常</el-radio>
                                            <el-radio :value="false">停用</el-radio>
                                        </el-radio-group>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="岗位">
                                        <el-select v-model="addFormData.post" placeholder="请选择角色" clearable>
                                            <el-option label="人事部经理" value="人事部经理"></el-option>
                                            <el-option label="研发岗" value="研发岗"></el-option>
                                            <el-option label="运营岗" value="运营岗"></el-option>
                                            <el-option label="HR" value="HR"></el-option>
                                            <el-option label="销售岗" value="销售岗"></el-option>
                                            <el-option label="算法岗" value="算法岗"></el-option>
                                            <el-option label="数据分析师" value="数据分析师"></el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="角色">
                                        <el-select v-model="addFormData.role" placeholder="请选择角色" clearable>
                                            <el-option label="超级管理员" value="0">
                                                <template #label="{ label, value }">
                                                    <span style="font-weight: bold">{{ label }}</span>
                                                </template>
                                            </el-option>
                                            <el-option label="租户管理员" value="1">
                                                <template #label="{ label, value }">
                                                    <span>{{ label }}</span>
                                                </template>
                                            </el-option>
                                            <el-option label="普通用户" value="2">
                                                <template #label="{ label, value }">
                                                    <span>{{ label }}</span>
                                                </template>
                                            </el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-form-item label="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;备注" prop="content">
                                <QuillEditorVue ref="quillEditor" :initial-content="addFormData.remark"
                                    @content-updated="handleContentUpdate">
                                </QuillEditorVue>

                            </el-form-item>
                        </el-form>
                    </div>
                    <template #footer>
                        <span class="dialog-footer">
                            <el-button @click="visible = false; resetForm()">取消</el-button>
                            <el-button type="primary" @click="submitForm">提交</el-button>
                        </span>
                    </template>
                </el-dialog>

                <!-- 修改用户 -->
                <el-dialog v-model="visibleUpdate" title="修改用户" width="60%" @close="resetForm()">
                    <div>
                        <el-form :model="updateFormData" label-width="90px" :rules="rules" ref="ruleForm">

                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="用户昵称" prop="nickname">
                                        <el-input v-model="updateFormData.nickname" placeholder="请输入用户昵称"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="上级部门">
                                        <el-select v-model="updateFormData.companyId" placeholder="上级部门"
                                            @change="fetchDepartmentList($event)">
                                            <el-option v-for="item in tableDataTree" :key="item.companyId"
                                                :label="item.name" :value="item.companyId" />
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="归属部门">
                                        <el-select v-model="updateFormData.departmentId" placeholder="归属部门">
                                            <el-option v-for="item in departmentData" :key="item.id" :label="item.name"
                                                :value="item.id" />
                                            <el-option v-if="!departmentData.length" disabled label="暂无部门，请先添加部门"
                                                value="null" />
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="手机号码">
                                        <el-input v-model="updateFormData.tel" placeholder="请输入手机号码"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="邮箱">
                                        <el-input v-model="updateFormData.email" placeholder="请输入邮箱"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="用户名称">
                                        <el-input v-model="updateFormData.name" placeholder="请输入用户名称"
                                            disabled></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="用户密码" prop="pwd">
                                        <!-- 密码输入框，包含切换可见性的眼睛图标 -->
                                        <el-input v-model="updateFormData.pwd" placeholder="请输入用户密码" show-password>
                                        </el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="用户性别">
                                        <el-select v-model="updateFormData.gender" placeholder="请选择性别">
                                            <el-option label="男" :value="true"></el-option>
                                            <el-option label="女" :value="false"></el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="状态">
                                        <el-radio-group v-model="updateFormData.status">
                                            <el-radio :value="true">正常</el-radio>
                                            <el-radio :value="false">停用</el-radio>
                                        </el-radio-group>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="岗位">
                                        <el-select v-model="updateFormData.post" placeholder="请选择角色" clearable>
                                            <el-option label="人事部经理" value="人事部经理"></el-option>
                                            <el-option label="研发岗" value="研发岗"></el-option>
                                            <el-option label="运营岗" value="运营岗"></el-option>
                                            <el-option label="HR" value="HR"></el-option>
                                            <el-option label="销售岗" value="销售岗"></el-option>
                                            <el-option label="算法岗" value="算法岗"></el-option>
                                            <el-option label="数据分析师" value="数据分析师"></el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="角色">
                                        <el-select v-model="updateFormData.role" placeholder="请选择角色" clearable>
                                            <el-option label="超级管理员" value="0">
                                                <template #label="{ label, value }">
                                                    <span style="font-weight: bold">{{ label }}</span>
                                                </template>
                                            </el-option>
                                            <el-option label="租户管理员" value="1">
                                                <template #label="{ label, value }">
                                                    <span>{{ label }}</span>
                                                </template>
                                            </el-option>
                                            <el-option label="普通用户" value="2">
                                                <template #label="{ label, value }">
                                                    <span>{{ label }}</span>
                                                </template>
                                            </el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-form-item label="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;备注" prop="content">
                                <QuillEditorVue ref="quillEditor1" :initial-content="updateFormData.remark"
                                    @content-updated="handleContentUpdate1">
                                </QuillEditorVue>

                            </el-form-item>
                        </el-form>
                    </div>
                    <template #footer>
                        <span class="dialog-footer">
                            <el-button @click="visibleUpdate = false; resetForm()">取消</el-button>
                            <el-button type="primary" @click="submitEditForm">提交</el-button>
                        </span>
                    </template>
                </el-dialog>


            </el-col>
        </el-row>
    </div>
</template>

<script setup lang="ts">
import { ref, nextTick, Ref, computed, onMounted, reactive } from 'vue';
import { Plus, Edit, Delete, Download, EditPen, Search, Refresh, Upload } from '../../../node_modules/@element-plus/icons-vue';
import { ElMessage, ElMessageBox, ElTable, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElButton, ElCheckbox, FormInstance } from 'element-plus';
import { type Filters, type DepartmentItem, type Company, type UserItem, getCompanyList, getUserList, editUserService, getUserListByClickTree, getDepartmentList, addUserService, editUserService1, deleteUserService, exportFile, searchUserService, searchDepartmentService } from '../../api/userApi.ts'
import QuillEditorVue from '../../components/commonUse/Editor.vue';
import request from '../../until/request.ts';
import ChinaMap from '../../components/commonUse/ChinaMap.vue';
import Gender from '../../components/commonUse/Gender.vue'

interface TreeItem {
    label: string;
    children?: TreeItem[];
}
//定义节点文本和子节点的键名
const defaultProps = {
    children: 'children',
    label: 'label',
}
const tableDataTree = ref<Company[]>([]);

// 转换函数
const convertToTreeData = (companies: Company[]): TreeItem[] => {
    return companies.map(company => ({
        label: company.name,
        companyId: company.companyId, // 存储公司ID
        id: company.companyId, // 使用公司ID作为根节点ID
        children: company.departmentList.map(department => ({
            label: department.name,
            id: department.id, // 存储部门ID
            companyId: company.companyId, // 存储公司ID
        }))
    }));
};
// 计算属性自动处理转换
const rootData: any = computed(() => [
    {
        label: "测盟汇",
        children: convertToTreeData(tableDataTree.value)
    }
]);
//获取公司列表
const fetchCompanyList = async () => {
    try {
        const res = await getCompanyList();
        tableDataTree.value = res;
    } catch (error) {
        ElMessage.error("获取公司列表失败");
    }
};
fetchCompanyList();
// 点击节点
const handleNodeClick = async (data: TreeItem) => {
    console.log(data)
    // 获取部门列表
    addFormData.value.companyId = data.companyId;
    const res = await getUserListByClickTree(data.companyId, data.id);
    userList.value = res;
    pageination.total = userList.value.length
    handleCurrentChange(1);
    handleSizeChange(pageination.pageSize);
}
//搜索部门
const input2 = ref('');
const searchMethod = async () => {
    const res = await searchDepartmentService(input2.value);

    tableDataTree.value = res;
    ElMessage.success('搜索成功！');
}
//----------------------用户部分----------------------
const filters: Ref<Filters> = ref({
    name: '',
    tel: '',
    status: true,
    createTime: '',
});
const userList: Ref<UserItem[]> = ref([]);
const userListWithPagination: Ref<UserItem[]> = ref([]);
const fetchUserList = async () => {
    try {
        const res = await getUserList();
        userList.value = res;
        pageination.total = userList.value.length;
        handleCurrentChange(1);
        handleSizeChange(10);
    } catch (error) {
        ElMessage.error("获取用户列表失败");
    }
};
fetchUserList();
//处理状态开关
const handleStatusChange = async (user: UserItem) => {
    console.log(user.name + "的状态改变成：", user.status);
    // 这里添加更新到服务器的逻辑
    await editUserService(user);
    fetchUserList(); // 重新获取用户列表
    ElMessage.success("状态修改成功");
}
// 搜索功能
const search = async () => {
    userList.value = await searchUserService(filters.value);
    pageination.total = userList.value.length;
    handleCurrentChange(1);
    handleSizeChange(10);
    ElMessage.success('搜索成功！');
};

//重置搜索条件
const reset = () => {
    filters.value = {
        name: '',
        tel: '',
        status: true,
        createTime: '',
    };
    fetchUserList();
    ElMessage.success('重置成功！');
};
//----------导入部分--------
const fileInput = ref<HTMLInputElement | null>(null);

// 触发文件输入
function triggerFileInput() {
    fileInput.value?.click();
}

// 处理文件上传
function handleFileUpload(event: Event) {
    const target = event.target as HTMLInputElement;
    const file = target.files ? target.files[0] : null;
    if (file) {
        uploadFile(file);
    }
}

// 将文件发送到服务器
async function uploadFile(file: File) {
    const formData = new FormData();
    formData.append('file', file);

    try {
        const response = await request.post('/import/users', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        });
        console.log('文件上传成功:', response.data);
        ElMessage.success('文件导入成功');
        fetchUserList();
    } catch (error) {
        console.error('文件上传失败:', error);
        ElMessage.error('文件导入失败');
    }
}

//添加资讯
const visible = ref(false);

const addFormData = ref<UserItem>({
    name: '',
    pwd: '',
    role: '',
    status: true,
    createTime: '',
    tel: '',
    remark: '',
    imageURL: '',
    companyName: '',
    contacts: '',
    nickname: '',
    post: '',
    email: '',
    gender: true,
    employeeRole: null,
    companyId: null,
    departmentId: null,
    id: null
});
const openAddDialog = () => {
    visible.value = true;
    resetForm(); // 打开对话框时重置表单

};
//更新富文本编辑器内容
const quillEditor = ref(null);
const handleContentUpdate = (newContent: string) => {
    addFormData.value.remark = newContent;
}
//获取部门列表
const departmentData: Ref<DepartmentItem[]> = ref([]);
const fetchDepartmentList = async (newCompanyId: number) => {

    if (addFormData.value.companyId || updateFormData.value.companyId) {
        // 查找选中公司的完整信息
        const selectedCompany = tableDataTree.value.find(company => company.companyId === newCompanyId);
        if (selectedCompany) {
            // 确保 selectedCompany 不是 undefined 之后再访问 .name 属性
            addFormData.value.companyName = selectedCompany.name;
            console.log(selectedCompany.name);
            const res = await getDepartmentList(selectedCompany.name);
            departmentData.value = res;
            // 如果没有部门数据，清空已选择的部门 ID
            if (!departmentData.value.length) {
                addFormData.value.departmentId = null;
            }
        }

    }
};
// 实现提交功能
const submitForm = async () => {
    isAddForm.value = true
    if (ruleForm.value) {
        ruleForm.value.validate(async (valid: any) => {
            if (valid) {
                try {
                    const res = await addUserService(addFormData.value);
                    if (res.code == 0 || res.isOk == true) {
                        ElMessage.success('提交成功！');
                        visible.value = false;
                        // 提交后清空表单
                        resetForm();
                        fetchUserList();
                    } else {
                        ElMessage.error(res.msg);
                    }
                } catch (error) {
                    console.error(error)
                }

            } else {
                ElMessage({
                    message: '请提交正确的用户信息！包括部门信息！',
                    type: 'error',
                });
                return false;
            }
        });
    }
};

//重置表单
const resetForm = async () => {
    addFormData.value = {
        name: '',
        pwd: '',
        role: '',
        status: true,
        createTime: '',
        tel: '',
        remark: '',
        imageURL: '',
        companyName: '',
        contacts: '',
        nickname: '',
        post: '',
        email: '',
        gender: true,
        employeeRole: null,
        companyId: null,
        departmentId: null,
        id: null

    };

    updateFormData.value = {
        name: '',
        pwd: '',
        role: '',
        status: true,
        createTime: '',
        tel: '',
        remark: '',
        imageURL: '',
        companyName: '',
        contacts: '',
        nickname: '',
        post: '',
        email: '',
        gender: true,
        employeeRole: null,
        companyId: null,
        departmentId: null,
        id: null
    };
    //重置表单和重置验证状态
    if (ruleForm.value) {
        ruleForm.value.resetFields();
    }
};
//修改资讯
const visibleUpdate = ref(false);
const updateFormData = ref<UserItem>({
    name: '',
    pwd: '',
    role: '',
    status: true,
    createTime: '',
    tel: '',
    remark: '',
    imageURL: '',
    companyName: '',
    contacts: '',
    nickname: '',
    post: '',
    email: '',
    gender: true,
    employeeRole: null,
    companyId: null,
    departmentId: null,
    id: null
});
//更新富文本编辑器内容
const quillEditor1 = ref(null);
const handleContentUpdate1 = (newContent: string) => {
    updateFormData.value.remark = newContent;

}

//编辑
const editUsers = async (index: number, row: UserItem) => {

    // 确保 Vue 的更新周期完成，确保所有数据被处理
    await nextTick();
    // 使用传入的行数据填充表单
    updateFormData.value = {
        ...row // 展开row对象，并将其值赋给updateFormData
    };
    fetchDepartmentList(row.companyId);
    console.log(row.companyId);
    visibleUpdate.value = true;
};
import { useRouter } from 'vue-router';
import { useUserInfoStore, type UserInfo } from '../../store/userInfo.ts'
const userInfoStore = useUserInfoStore()
const userId = userInfoStore.info.id
let router = useRouter()
import { useTokenStore } from '../../store/token.ts'
const tokenStore = useTokenStore()
//提交修改资讯的表单
const submitEditForm = async () => {
    isAddForm.value = false
    if (ruleForm.value) {
        ruleForm.value.validate(async (valid: any) => {
            console.log("enter")
            if (valid && updateFormData.value.companyId && updateFormData.value.departmentId) {
                try {
                    const res = await editUserService1(updateFormData.value);
                    if (res.code == 0 || res.isOk == true) {
                        ElMessage.success('提交成功！');
                        visible.value = false;
                        // 提交后清空表单
                        resetForm();
                        fetchUserList();
                        visibleUpdate.value = false;
                        //如果是修改自己的信息，重新登录
                        if (updateFormData.value.id === userId) {
                            //清空后端存储的token
                            const response = await request.post('/user/logout');
                            if (response.data.code === 0) {
                                //清空用户信息，和token
                                tokenStore.removeToken();
                                userInfoStore.removeInfo();
                                
                                //跳转到登录页面
                                setTimeout(() => {
                                    ElMessage.warning('身份信息过期，请重新登录！');
                                    router.push('/')
                                }, 1000);
                                
                            }
                        }
                    } else {
                        ElMessage.error(res.msg);
                    }
                } catch (error) {
                    console.error('Login failed:', error)
                    // 可以在这里添加错误处理，例如显示错误消息给用户
                }

            } else {
                ElMessage({
                    message: '请提交正确的用户信息!',
                    type: 'error',
                });
                return false;
            }
        })

    }
};
//删除用户
const deleteUsers = async (index: number, row: UserItem) => {

    const name = row.name;
    ElMessageBox.confirm('确定删除该 "' + name + '" 的用户吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        // 实现删除功能
        await deleteUserService(row);
        ElMessage.success('删除成功！');
        fetchUserList();
    }).catch(() => {
        ElMessage.info('已取消删除');
    });

};
//选择条目功能
//不能实现批量添加，删除，修改，只能对选中的第一条数据进行操作
const selectedRows = ref<UserItem[]>([]);
const handleSelectionChange = (selection: UserItem[]) => {
    selectedRows.value = selection;
};
const editSelectedMeeting = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要编辑的新闻');
        return;
    }
    //选取第一条选中的会议进行编辑
    const row = selectedRows.value[0];
    editUsers(0, row);
};
const deleteSelectedMeeting = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要删除的新闻');
        return;
    }
    // 遍历选中的所有咨询条目，并逐个执行删除操作
    for (const row of selectedRows.value) {

        try {
            await deleteUserService(row);

        } catch (error) {
            ElMessage.error('删除失败！');
        }
    }
    ElMessage.success('删除成功！');
    fetchUserList();
};
//导出excel
const exportExcle = () => {
    exportFile();
    ElMessage.success('导出成功！');
};

//表单验证
const users = ref<any>([]);
const isShown = ref(false)//ELMessage解锁(创建者)
onMounted(async () => {
    users.value = await getUserList();
});
//表单选择
const isAddForm = ref(true)
// const userNames = ref<String[]>([]);
const ruleForm = ref<FormInstance>()
const rules = {
    nickname: [
        { required: true, message: '请输入用户昵称！', trigger: 'blur' }
    ],
    name: [
        { required: true, message: '请输入用户名！', trigger: 'blur' },
        {
            validator: (rule: any, value: any, callback: any) => {
                const isGet = ref(false);
                users.value.forEach((user: UserItem) => {
                    if (user.name == value && isAddForm.value) {
                        isGet.value = true;
                        callback('输入的用户名已被占用');
                        if (isShown.value == false) {
                            ElMessage({
                                message: '输入的用户名已被占用！或者尝试刷新页面',
                                type: 'error',
                            });
                            isShown.value = true;//ELMessage加锁
                        }
                        return false;
                    }
                })
                callback();
                return true;

            }, trigger: 'blur'
        }
    ],
    pwd: [
        { required: true, message: '请输入密码！', trigger: 'blur' }
    ]
}


//分页
const pageination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 64
});
//当每页条数发生了变化，调用此函数
const handleSizeChange = (val: number) => {
    pageination.pageSize = val;
    userListWithPagination.value = userList.value.slice((pageination.currentPage - 1) * pageination.pageSize, Math.min((pageination.currentPage) * pageination.pageSize, pageination.total));
};
//当前页码发生变化，调用此函数
const handleCurrentChange = (val: number) => {
    pageination.currentPage = val;
    userListWithPagination.value = userList.value.slice((pageination.currentPage - 1) * pageination.pageSize, Math.min((pageination.currentPage) * pageination.pageSize, pageination.total));
};
</script>

<style scoped>
.pagination-fixed {
    text-align: center;
}

.pagination-container {
    /* position: fixed; */
    display: flex;
    margin-top: 25px;
    /* margin-bottom: -2000px; */
    justify-content: center;
    width: 100%;
    z-index: 1000;
    /* 确保分页条在最上层 */
}
</style>